package cn.willbj.brief.rt.util.concurrent.CompletableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 【对象方法】
 *
 * acceptEither 方法
 * 两个CompletionStage，谁执行返回的结果快，我就用那个CompletionStage的结果进行下一步的消耗操作。
 *
 * 注意:acceptEither与applyToEither的区别之一是，后者没有返回值
 *
 * 链接：https://www.jianshu.com/p/6bac52527ca4
 * @date 2020/12/1
 */
public class Demo10 {

    private static final ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*2);

    public static void main(String[] args) throws Exception {
        Demo10.test01();
    }

    /**
     * 执行顺序:(acceptEither方法，主体哪个执行快，参数是哪个)没有返回值
     * pool-1-thread-1 : num1
     * 我是pool-1-thread-3 : return_value01
     * pool-1-thread-2 : num2
     */
    public static void test01()throws Exception{
        CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : num1");
            return "return_value01";
        }, es);

        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : num2");
            return "return_value02";
        }, es);


        // x参数为future01和future02的，执行比较快的业务结果
        future01.acceptEitherAsync(future02, (x)->{
            System.out.println("我是"+Thread.currentThread().getName() + " : "+x);
        }, es);
    }

}
